package com.shiwenping.reply.data.local;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.shiwenping.reply.data.DataSource;
import com.shiwenping.reply.data.RealmUtil;
import com.shiwenping.reply.net.domain.FaqItemResult;
import com.shiwenping.reply.net.domain.FileItemResult;
import com.shiwenping.reply.tools.AllUtils;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 本地数据库
 *
 * @author shiwenping
 * @date 17-11-10 上午10:04
 */

public class LocalDataSource implements DataSource {
    private Realm realm;

    private Realm getRealm() {
        if (realm == null) {
            realm = RealmUtil.getRealm();
        }
        return realm;
    }

    @Override
    public Observable<List<FaqItemResult>> getFaqList(boolean isLocal,String cateName) {
        return Observable.just(isLocal)
                .flatMap(aBoolean -> {
//                    List<FaqItemResult> list = getRealm()
//                            .where(FaqItemResult.class)
//                            .like("faq_tag","%"+cateName+"%")
//                            .findAll();
                    List<FaqItemResult> list =null;
                    RealmQuery<FaqItemResult> realmQuery = getRealm()
                            .where(FaqItemResult.class);
                    if (TextUtils.isEmpty(cateName))
                    {
                        list = realmQuery.findAll();
                    }else {
                        list = realmQuery.like("faq_tag","*"+cateName+"*").findAll();
                    }
                    return Observable.just(list);
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread());
    }

    @Override
    public Observable<List<FileItemResult>> getFileList(boolean isLocal,String cateName) {
        return Observable.just(isLocal)
                .flatMap(aBoolean -> {
                    List<FileItemResult> list =null;
                     RealmQuery<FileItemResult> realmQuery = getRealm()
                            .where(FileItemResult.class);
                            if (TextUtils.isEmpty(cateName))
                            {
                                list = realmQuery.findAll();
                            }else {
                            list = realmQuery.like("file_tag","*"+cateName+"*").findAll();
                            }
                    return Observable.just(list);
                });
    }
}
